<template>
  <a-drawer
    :open="visible"
    title=""
    :width="500"
    placement="right"
    :closable="false"
    :body-style="{ padding: 0, background: '#f5f7fa' }"
    class="school-detail-drawer"
    @update:open="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <!-- 自定义头部 -->
    <div class="drawer-header">
      <div class="header-content">
        <div class="school-info">
          <div class="school-avatar">
            <a-avatar
              :src="schoolDetail?.schoolAvatar"
              :size="48"
              shape="square"
              class="school-logo"
            >
              <template #icon>
                <BankOutlined />
              </template>
            </a-avatar>
          </div>
          <div class="school-text">
            <h3 class="school-name">{{ schoolDetail?.schoolName || '加载中...' }}</h3>
            <p class="school-campus">{{ schoolDetail?.campuses || '暂无校区信息' }}</p>
          </div>
        </div>
        <a-button type="text" @click="handleClose" class="close-btn">
          <CloseOutlined />
        </a-button>
      </div>
    </div>

    <!-- 统计卡片区 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card user-count">
          <div class="stat-icon">
            <UserOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ schoolDetail?.userCount || 0 }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </div>

        <div class="stat-card campus-info">
          <div class="stat-icon">
            <EnvironmentOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ schoolDetail?.campusCount || 1 }}</div>
            <div class="stat-label">校区数量</div>
          </div>
        </div>

        <div class="stat-card status-info">
          <div class="stat-icon">
            <CheckCircleOutlined v-if="schoolDetail?.schoolStatus === 'active'" />
            <CloseCircleOutlined v-else />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getStatusText() }}</div>
            <div class="stat-label">运营状态</div>
          </div>
        </div>

        <div class="stat-card location-info" @click="handleShowMap">
          <div class="stat-icon">
            <GlobalOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ hasLocation() ? '已设置' : '未设置' }}</div>
            <div class="stat-label">地理位置</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 基本信息区 -->
    <div class="info-section">
      <div class="section-header">
        <h4><BankOutlined /> 基本信息</h4>
      </div>
      <div class="info-content">
        <a-skeleton :loading="loading" active :paragraph="{ rows: 4 }">
          <div class="info-grid">
            <div class="info-item">
              <label>学校名称：</label>
              <span>{{ schoolDetail?.schoolName || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>所属校区：</label>
              <span>{{ schoolDetail?.campuses || '暂无' }}</span>
            </div>
            <div class="info-item">
              <label>运营状态：</label>
              <a-tag :color="schoolDetail?.schoolStatus === 'active' ? 'success' : 'error'">
                {{ getStatusText() }}
              </a-tag>
            </div>
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ schoolDetail?.createdTime || '暂无' }}</span>
            </div>
            <div
              v-if="schoolDetail?.longitude && schoolDetail?.latitude"
              class="info-item location-item"
            >
              <label>地理位置：</label>
              <div class="location-content">
                <div class="coordinates">
                  {{ schoolDetail.longitude.toFixed(4) }}, {{ schoolDetail.latitude.toFixed(4) }}
                </div>
                <a-button type="link" size="small" @click="handleShowMap" class="view-map-btn">
                  <EnvironmentOutlined />
                  查看地图
                </a-button>
              </div>
            </div>
          </div>
        </a-skeleton>
      </div>
    </div>

    <!-- 用户管理区 -->
    <div class="users-section">
      <div class="section-header">
        <h4><TeamOutlined /> 用户管理 ({{ pagination.total }})</h4>
      </div>

      <!-- 搜索和筛选 -->
      <div class="users-filter">
        <div class="filter-row">
          <a-input
            v-model:value="userSearchParams.keyword"
            placeholder="搜索用户名、邮箱..."
            allow-clear
            @change="handleUserSearch"
            class="search-input"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="users-list">
        <a-skeleton :loading="userLoading" active :paragraph="{ rows: 3 }">
          <div v-if="userList.length > 0" class="user-items">
            <div
              v-for="user in userList"
              :key="user.id"
              class="user-item"
              @click="handleUserDetail(user)"
            >
              <div class="user-avatar">
                <a-avatar :src="user.avatar" :size="40">
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
              </div>
              <div class="user-info">
                <div class="user-name">{{ user.nickName }}</div>
                <div class="user-email">{{ user.email || '暂无邮箱' }}</div>
              </div>
              <div class="user-meta">
                <div class="user-time">{{ formatTime(user.lastLoginTime) }}</div>
              </div>
            </div>
          </div>

          <div v-else-if="!userLoading" class="empty-users">
            <a-empty description="暂无用户数据" />
          </div>
        </a-skeleton>

        <!-- 加载更多 -->
        <div
          v-if="userList.length > 0 && pagination.current * pagination.pageSize < pagination.total"
          class="load-more"
        >
          <a-button @click="loadMoreUsers" :loading="userLoading" block type="dashed">
            加载更多
          </a-button>
        </div>
      </div>
    </div>

    <!-- 地图弹窗 -->
    <a-modal
      v-model:open="mapVisible"
      :title="`${schoolDetail?.schoolName} - 位置信息`"
      :footer="null"
      width="600px"
      @after-close="handleMapModalClose"
    >
      <div class="map-container">
        <div id="schoolMapContainer" style="height: 350px; width: 100%"></div>
      </div>
    </a-modal>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import {
  BankOutlined,
  CloseOutlined,
  UserOutlined,
  EnvironmentOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  GlobalOutlined,
  TeamOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue'
import { schoolService } from '@/api/school'
import { userService, type UserPageParams } from '@/api/user'
import { createReadonlyMap, destroyMap } from '@/utils/mapUtils'
import type { School, User } from '@/types'

// 扩展School类型，添加userCount字段
interface SchoolDetail extends Omit<School, never> {
  userCount?: number
  campusCount?: number
}

interface Props {
  visible: boolean
  schoolId?: number
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态管理
const loading = ref(false)
const userLoading = ref(false)
const mapVisible = ref(false)
const schoolDetail = ref<SchoolDetail | null>(null)
const userList = ref<User[]>([])
let currentMap: any = null

// 搜索参数
const userSearchParams = reactive({
  keyword: '',
  schoolId: 0,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// 防抖搜索定时器
let searchTimeout: ReturnType<typeof setTimeout> | null = null

// 监听visible变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.schoolId) {
      loadSchoolDetail()
      loadUserList(true)
    } else {
      resetData()
    }
  }
)

// 监听schoolId变化
watch(
  () => props.schoolId,
  (newSchoolId) => {
    if (newSchoolId && props.visible) {
      loadSchoolDetail()
      loadUserList(true)
    }
  }
)

// 加载学校详情
const loadSchoolDetail = async () => {
  if (!props.schoolId) return

  try {
    loading.value = true
    const result = await schoolService.getSchoolDetail(props.schoolId)
    schoolDetail.value = result
  } catch (error) {
    message.error('加载学校详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载用户列表
const loadUserList = async (reset = false) => {
  if (!props.schoolId) return

  try {
    userLoading.value = true

    if (reset) {
      pagination.current = 1
      userList.value = []
    }

    const params: UserPageParams = {
      nickName: userSearchParams.keyword,
      schoolId: props.schoolId,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }

    const result = await userService.getUserPage(params)

    if (reset) {
      userList.value = result.result || []
    } else {
      userList.value.push(...(result.result || []))
    }

    pagination.total = result.total || 0
  } catch (error) {
    message.error('加载用户列表失败')
    console.error(error)
  } finally {
    userLoading.value = false
  }
}

// 加载更多用户
const loadMoreUsers = () => {
  pagination.current++
  loadUserList(false)
}

// 处理用户搜索
const handleUserSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }

  searchTimeout = setTimeout(() => {
    loadUserList(true)
  }, 300)
}

// 处理用户详情
const handleUserDetail = (user: User) => {
  // 这里可以实现用户详情弹窗或跳转
  message.info(`查看用户: ${user.nickName}`)
}

// 显示地图
const handleShowMap = async () => {
  if (!schoolDetail.value?.longitude || !schoolDetail.value?.latitude) {
    message.warning('该学校未设置地理位置')
    return
  }

  mapVisible.value = true

  await nextTick()
  try {
    currentMap = await createReadonlyMap('schoolMapContainer', {
      longitude: schoolDetail.value.longitude,
      latitude: schoolDetail.value.latitude,
      title: schoolDetail.value.schoolName,
    })
  } catch (error) {
    console.error('地图加载失败:', error)
    message.error('地图加载失败')
  }
}

// 地图弹窗关闭
const handleMapModalClose = () => {
  destroyMap()
  currentMap = null
}

// 关闭侧边栏
const handleClose = () => {
  emit('update:visible', false)
}

// 重置数据
const resetData = () => {
  schoolDetail.value = null
  userList.value = []
  userSearchParams.keyword = ''
  pagination.current = 1
  pagination.total = 0
  if (searchTimeout) {
    clearTimeout(searchTimeout)
    searchTimeout = null
  }
}

// 获取状态文本
const getStatusText = () => {
  return schoolDetail.value?.schoolStatus === 'active' ? '正常运营' : '暂停运营'
}

// 检查是否有位置信息
const hasLocation = () => {
  return !!(schoolDetail.value?.longitude && schoolDetail.value?.latitude)
}

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return '从未登录'
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) return '今天'
  if (days === 1) return '昨天'
  if (days < 7) return `${days}天前`
  if (days < 30) return `${Math.floor(days / 7)}周前`
  return `${Math.floor(days / 30)}月前`
}
</script>

<style scoped lang="scss">
.school-detail-drawer {
  :deep(.ant-drawer-content) {
    background: #f5f7fa;
  }

  :deep(.ant-drawer-body) {
    padding: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.drawer-header {
  background: url('https://lanyun-tc.oss-cn-guangzhou.aliyuncs.com/003.jpeg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  color: white;
  padding: 20px;
  position: relative;

  // 添加半透明遮罩层
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5); // 黑色半透明遮罩
    z-index: 1;
  }

  // 确保内容在遮罩层之上
  .header-content {
    position: relative;
    z-index: 2;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .school-info {
    display: flex;
    align-items: center;
    gap: 16px;

    .school-logo {
      border: 2px solid rgba(255, 255, 255, 0.2);
    }

    .school-text {
      .school-name {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: white;
      }

      .school-campus {
        margin: 4px 0 0 0;
        font-size: 14px;
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }

  .close-btn {
    color: white;
    border: none;

    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }
  }
}

.stats-section {
  padding: 20px;
  background: white;
  margin-bottom: 16px;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .stat-card {
    background: white;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
      border-color: #1890ff;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
      transform: translateY(-2px);
    }

    .stat-icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }

    .stat-content {
      flex: 1;

      .stat-number {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 12px;
        color: #666;
      }
    }

    &.user-count {
      .stat-icon {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
      }

      .stat-number {
        color: #667eea;
      }
    }

    &.campus-info {
      .stat-icon {
        background: linear-gradient(135deg, #f093fb, #f5576c);
        color: white;
      }

      .stat-number {
        color: #f5576c;
      }
    }

    &.status-info {
      .stat-icon {
        background: linear-gradient(135deg, #4facfe, #00f2fe);
        color: white;
      }

      .stat-number {
        color: #4facfe;
      }
    }

    &.location-info {
      .stat-icon {
        background: linear-gradient(135deg, #43e97b, #38f9d7);
        color: white;
      }

      .stat-number {
        color: #43e97b;
      }
    }
  }
}

.info-section,
.users-section {
  background: white;
  margin-bottom: 16px;

  .section-header {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;

    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #262626;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .info-content {
    padding: 20px;

    .info-grid {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .info-item {
      display: flex;
      align-items: center;

      label {
        width: 80px;
        color: #666;
        font-size: 14px;
        margin-right: 12px;
        flex-shrink: 0;
      }

      span {
        color: #262626;
        font-size: 14px;
      }

      &.location-item {
        align-items: flex-start;

        .location-content {
          display: flex;
          flex-direction: column;
          gap: 8px;

          .coordinates {
            color: #262626;
            font-size: 14px;
            font-family: monospace;
          }

          .view-map-btn {
            padding: 0;
            height: auto;
            font-size: 12px;
            align-self: flex-start;
          }
        }
      }
    }
  }
}

.users-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;

  .users-filter {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;

    .filter-row {
      display: flex;
      gap: 12px;
      align-items: center;

      .search-input {
        flex: 1;
      }
    }
  }

  .users-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px 20px;

    .user-items {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .user-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      background: #fafafa;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: #f0f8ff;
        transform: translateX(4px);
      }

      .user-avatar {
        flex-shrink: 0;
      }

      .user-info {
        flex: 1;
        min-width: 0;

        .user-name {
          font-size: 14px;
          font-weight: 500;
          color: #262626;
          margin-bottom: 4px;
        }

        .user-email {
          font-size: 12px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .user-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 4px;

        .user-time {
          font-size: 11px;
          color: #999;
        }
      }
    }

    .empty-users {
      text-align: center;
      padding: 40px 0;
    }

    .load-more {
      margin-top: 16px;
    }
  }
}

.map-container {
  #schoolMapContainer {
    border-radius: 8px;
    overflow: hidden;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .school-detail-drawer {
    :deep(.ant-drawer-content) {
      width: 100vw !important;
    }
  }

  .stats-section {
    .stats-grid {
      grid-template-columns: 1fr;
      gap: 12px;
    }
  }
}
</style> 